<template>
  <div class="cusList">
    <el-row v-if="!$route.params.showHistory">
      <el-col :span="8">
        <el-input v-model="wd" placeholder="用户名、手机号、邮箱、ssoid搜索" @keyup.enter.native="submitSearch"></el-input>
      </el-col>
      <el-col :span="3">
        <el-button type="primary" style="margin-left:10px;" @click="submitSearch">搜索</el-button>
      </el-col>
    </el-row>
    <el-row v-if="!$route.params.showHistory">
      <span>注册来源：</span>
      <el-select v-model="source" style="margin-right:30px;">
        <el-option label="所有" value=""></el-option>
        <el-option v-for="item,n in regSource" :label="item.name" :value="item.enumStr" :key="n.toString()"></el-option>
      </el-select>
      <el-select v-model="groupType" @change="groupList.list = [];group=null">
        <el-option label="所属群组" :value="null"></el-option>
        <el-option label="静态群组" :value="2"></el-option>
        <el-option label="动态群组" :value="1"></el-option>
      </el-select>
      <el-select v-model="group" remote filterable clearable :remote-method="handleSearchGroup" :loading="groupLoading" placeholder="请输入关键词">
        <el-option v-for="item,n in groupList.list" :value="item.id" :label="item.name" :key="n.toString()"></el-option>
      </el-select>
    </el-row>
    <el-row v-if="!$route.params.showHistory">
      <el-button type="text" @click="seniorFilter = !seniorFilter">{{seniorFilter?'收起':'更多'}}筛选条件</el-button>
      <div v-show="seniorFilter">
        <g-filter ref="filters"></g-filter>
        <el-row style="margin-top:-10px;text-align:center;">
          <el-button type="button" @click="handleSeniorFilter">搜索</el-button>
          <el-button type="button" @click="handleClearFilter">清空</el-button>
        </el-row>
      </div>
    </el-row>
    <el-row v-if="!$route.params.showHistory">
      <el-button type="button" @click="dialogVisible1 = true" :disabled="!!group">保存为动态群组</el-button>
      <el-dropdown trigger="click" @command="handleAddStatic">
        <el-button type="button">
          保存为静态群组<i class="el-icon-caret-bottom el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="width:140px">
          <el-dropdown-item command="1">保存筛选结果</el-dropdown-item>
          <el-dropdown-item command="2" :disabled="!selections.length">保存勾选选项</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-dropdown trigger="click" @command="handleAddTag">
        <el-button type="button">
          添加标签<i class="el-icon-caret-bottom el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="1">为筛选结果添加</el-dropdown-item>
          <el-dropdown-item command="2">为勾选选项添加</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button type="text" class="fr" @click="dialogVisible4=true">配置显示字段</el-button>
    </el-row>
    <el-table v-loading="tbLoading" element-loading-text="拼命加载中" :data="cusList.list" stripe class="table" @selection-change="handleSelectChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <template v-for="item,n in cusTh">
        <el-table-column v-if="n=='用户头像'" :label="n" className="is-center">
          <template slot-scope="scope">
            <img src="" alt="">
          </template>
        </el-table-column>
        <el-table-column v-else-if="n=='ssoid'" label="ssoid">
          <template slot-scope="scope">
            <el-button type="text" @click="$router.push({name: 'CustomerOrderDetail', params: {sid: scope.row.ssoid}})" style="cursor:pointer;">{{scope.row.ssoid}}</el-button>
          </template>
        </el-table-column>
        <el-table-column v-else :label="n" :prop="item" :key="n.toString()" className="is-center"></el-table-column>
      </template>
      <el-table-column label="标签" className="is-center">
        <template slot-scope="scope">
          {{customerTagsString(scope.row.tags)}}
        </template>
      </el-table-column>
      <el-table-column label="操作" className="is-center">
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="$router.push({name: 'CustomerDetail', params: {sid: scope.row.ssoid}})">会员详情</el-button>
          <el-button size="small" type="text" @click="$router.push({name: 'CustomerOrderDetail', params: {sid: scope.row.ssoid}})">交易记录</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page.sync="page"
        :page-size.sync="size"
        layout="sizes, total, prev, pager, next, jumper"
        :total="cusList.page.total"
        :page-sizes="[10, 30, 50, 100]"
        @current-change="searchType == 'custom' ? submitSearch() : handleSeniorFilter()"
        @size-change="handleSizeChange">
      </el-pagination>
    </div>
    <!-- 保存为动态群组弹层 -->
    <el-dialog title="保存为动态群组" :visible.sync="dialogVisible1" width="30%">
      <el-form label-width="70px">
        <el-form-item label="群组名称">
          <el-input v-model="smartGroup"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveAsSmart" :loading="isSaving">保存</el-button>
      </div>
    </el-dialog>
    <!-- 添加标签弹层 -->
    <el-dialog title="添加标签" :visible.sync="dialogVisible2" width="30%">
      <el-form label-width="70px">
        <el-form-item label="标签名称">
          <el-select v-model="tagID" remote filterable clearable :remote-method="queryTagAsync" :loading="groupLoading" placeholder="请输入标签关键词" style="width:100%">
            <el-option v-for="item,n in tagList.list" :value="item.id" :label="item.name + ' （分类：' + item.pname + '）'" :key="n.toString()"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" :loading="isSaving" @click="handleSaveTag">保存</el-button>
      </div>
    </el-dialog>
    <!-- 保存为静态群组弹层 -->
    <el-dialog title="保存静态群组" :visible.sync="dialogVisible3" width="30%">
      <el-form label-width="120px">
        <el-form-item label="1">
          <el-input v-model="staticGroup"></el-input>
          <div slot="label"><el-radio v-model="ifNewStatic" :label="true">新建静态群组</el-radio></div>
        </el-form-item>
        <el-form-item label="1">
          <el-select 
            v-model="staticGroup2" 
            :remote-method="queryStaticGroup" 
            :loading="groupLoading" 
            placeholder="请输入群组关键词" 
            remote 
            filterable 
            clearable 
            :filter-method="filterStatic"
            style="width:100%">
            <el-option v-for="item,n in groupList.list" v-if="item.groupType===2" :value="item.id" :label="item.name" :key="n.toString()"></el-option>
          </el-select>
          <div slot="label"><el-radio v-model="ifNewStatic" :label="false">加入已有群组</el-radio></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="ifNewStatic?handleSaveAsNewStatic():handleSaveAsExistStatic()" :loading="isSaving">保存</el-button>
      </div>
    </el-dialog>
    <!-- 配置显示字段弹层 -->
    <cus-fields :show.sync="dialogVisible4" @success="initPageData"></cus-fields>
  </div>
</template>
<script>
  import Vue from 'vue'
  import {mapState, mapActions} from 'vuex'
  import gFilter from '@/components/common/cusManage/filter'
  import cusFields from '@/components/common/cusManage/setShowFields'
  // el-autoComplete 提示自定义样式
  Vue.component('autoComplete-item', {
    functional: true,
    render: function (h, ctx) {
      let item = ctx.props.item
      return h('li', ctx.data, [
        h('span', { attrs: { class: 'name' } }, [item.name])
      ])
    },
    props: {
      item: { type: Object, required: true }
    }
  })

  export default {
    data () {
      return {
        wd: '',
        source: '',
        groupType: null,
        group: null,
        seniorFilter: false,
        page: 1,
        size: 10,
        dialogVisible1: false,
        dialogVisible2: false,
        dialogVisible3: false,
        dialogVisible4: false,
        smartGroup: '',
        staticGroup: '',
        staticGroup2: '',
        tagID: '',
        ifNewStatic: true,
        tbLoading: true,
        isSaving: false,
        groupLoading: false,
        selections: []
      }
    },
    mounted () {
      this.initPageData()
    },
    components: {gFilter, cusFields},
    computed: {
      ...mapState({
        cusList: state => state.cusManage.cusList,
        groupId: state => state.userInfo.groupId,
        tagList: state => state.cusManage.tagList,
        regSource: state => state.cusManage.regSource,
        cusTh: state => state.cusManage.cusTh,
        groupList: state => state.cusManage.groupList,
        conditionsObj: state => state.cusManage.conditionsObj
      }),
      conditions () {
        let relationType = this.conditionsObj.relationType
        let conditionsGroup = this.conditionsObj.conditionsGroup
        return {relationType, conditionsGroup}
      }
    },
    methods: {
      filterStatic () {
        console.log(arguments)
        // alert()
        return false
      },
      ...mapActions(['getCustomers', 'getCustomerTags', 'createDynamicGroup', 'searchTags', 'addCusTagByID', 'addCusTagByCondition', 'createStaticGroup1', 'createStaticGroup2', 'getRegSource', 'getCustomerTh', 'getCusGroups2', 'getCusSenior', 'addToStaticGroup', 'addToStaticGroup2']),
      // 初始化页面数据
      initPageData () {
        let initData = this.$route.params.initData
        if (initData && initData.groupId) {
          this.group = initData.groupId
        }
        if (initData && initData.staticGroup2) {
          this.ifNewStatic = initData.ifNewStatic
          this.staticGroup2 = initData.staticGroup2
        }
        this.getRegSource()
        this.getCustomerTh()
          .then(() => {
            this.submitSearch()
          })
      },
      // 日期格式化
      dateFormat (date) {
        return this.$date.format(new Date(date), 'YYYY-MM-DD hh:mm:ss')
      },
      // 搜索会员列表
      submitSearch () {
        this.searchType = 'custom'
        this.tbLoading = true
        let fields = Object.values(this.cusTh)
        this.getCustomers({wd: this.wd, source: this.source, groupId: this.group, fields, page: this.page, size: this.size})
          .then(() => {
            this.tbLoading = false
            this.getCustomerTags()
          })
      },
      // 高级筛选
      handleSeniorFilter () {
        this.source = null
        this.group = null
        this.searchType = 'senior'
        let params = this.$_.cloneDeep(this.$refs.filters.conditions)
        let conditionNum = 0
        params.conditionsGroup.forEach((item, j) => {
          item.conditions.forEach((item2, i) => {
            if (!item2.fieldName || !item2.pattern || !item2.content) {
              item.conditions[i] = null
              if (!item.conditions.length) {
                params.conditionsGroup.splice(j, 1)
              }
            } else {
              conditionNum++
            }
          })
          item.conditions = item.conditions.filter(obj => !!obj)
        })
        params.fields = Object.values(this.cusTh)
        params.groupId = this.group
        params.size = this.size
        params.page = this.page
        if (conditionNum) {
          this.tbLoading = true
          this.getCusSenior(params)
            .then(() => {
              this.tbLoading = false
              this.getCustomerTags()
            })
        }
      },
      // 清空高级筛选条件
      handleClearFilter () {
        this.$refs.filters.clearFilter()
      },
      // 获取用户标签
      customerTagsString (tags) {
        if (tags) {
          return tags.map(item => {
            return item.name
          }).join(',')
        }
      },
      // 搜索群组
      handleSearchGroup (query) {
        if (query) {
          this.groupLoading = true
          this.getCusGroups2({wd: query, status: 1, type: this.groupType, size: 10, page: 1, customerType: 1})
            .then(() => {
              this.groupLoading = false
            })
        }
      },
      // 搜索静态群组
      queryStaticGroup (query) {
        if (query) {
          this.groupLoading = true
          this.getCusGroups2({wd: query, status: 1, type: 2, size: 10, page: 1, customerType: 1})
            .then(() => {
              this.groupLoading = false
            })
        }
      },
      // 改变分页大小
      handleSizeChange (size) {
        this.size = size
        this.submitSearch()
      },
      // 保存为动态群组
      handleSaveAsSmart () {
        if (!this.smartGroup) {
          this.$message.warning('请输入群组名称')
          return false
        }
        this.isSaving = true
        this.createDynamicGroup({groupName: this.smartGroup, groupCondition: this.conditions})
          .then(res => {
            this.isSaving = false
            if (res.data.code === 1) {
              this.dialogVisible1 = false
              this.$message.success('保存成功')
            }
          })
      },
      // 保存为静态群组弹层
      handleAddStatic (type) {
        this.dialogVisible3 = true
        this.addStaticType = type
      },
      // 保存为新静态群组
      handleSaveAsNewStatic () {
        if (!this.staticGroup) {
          this.$message.warning('请输入群组名称')
          return false
        }
        this.isSaving = true
        if (this.addStaticType === '2') { // 保存勾选选项
          let ssoids = this.selections.map(item => {
            return item.ssoid
          })
          let groupName = this.staticGroup
          this.createStaticGroup2({groupName, ssoids})
            .then((res) => {
              this.isSaving = false
              this.dialogVisible3 = false
              if (res.data.code === 1) {
                this.getCustomerTags()
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                })
              }
            })
        } else if (this.addStaticType === '1') { // 保存筛选结果
          let groupName = this.staticGroup
          let groupCondition = this.conditions
          groupCondition.groupId = this.group
          this.createStaticGroup1({groupName, groupCondition})
            .then((res) => {
              this.isSaving = false
              this.dialogVisible3 = false
              if (res.data.code === 1) {
                this.getCustomerTags()
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                })
              }
            })
        }
        this.staticGroup = ''
      },
      // 保存为已存在静态群组
      async handleSaveAsExistStatic () {
        if (!this.staticGroup2) {
          this.$message.warning('请选择群组')
          return false
        }
        this.isSaving = true
        if (this.addStaticType === '2') {
          const ssoids = this.selections.map(item => {
            return item.ssoid
          })
          const groupId = this.staticGroup2
          const res = await this.addToStaticGroup({groupId, ssoids})
          this.$message.success(res.data.msgZ)
          this.isSaving = false
          this.dialogVisible3 = false
        } else if (this.addStaticType === '1') {
          const res = await this.addToStaticGroup2({groupId: this.staticGroup2, condition: this.conditions})
          this.$message.success(res.data.msgZ)
          this.isSaving = false
          this.dialogVisible3 = false
        }
      },
      // 选择行
      handleSelectChange (selection) {
        this.selections = [...selection]
      },
      // 搜索标签
      queryTagAsync (queryString) {
        let wd = queryString
        let gid = this.groupId
        let page = 1
        let size = 10
        this.searchTags({wd, gid, page, size})
      },
      // 添加标签弹层
      handleAddTag (type) {
        this.addTagType = type
        this.dialogVisible2 = true
      },
      // 添加标签保存
      handleSaveTag () {
        this.isSaving = true
        if (this.addTagType === '2') {
          let ssoids = this.selections.map(item => {
            return item.ssoid
          })
          let tagId = this.tagID
          this.addCusTagByID({tagId, ssoids})
            .then(res => {
              this.isSaving = false
              this.dialogVisible2 = false
              if (res.data.code === 1) {
                this.getCustomerTags()
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                })
              }
            })
        } else if (this.addTagType === '1') {
          let tagId = this.tagID
          this.addCusTagByCondition({tagId, condition: this.conditions})
            .then(res => {
              this.isSaving = false
              this.dialogVisible2 = false
              if (res.data.code === 1) {
                this.getCustomerTags()
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                })
              }
            })
        }
        this.tagID = ''
      }
    }
  }
</script>
<style lang="scss">
  .cusList{
    .el-row{margin-bottom:15px;}
    .el-table{
      .el-button{margin:0 5px;}
    }
  }
</style>
